import { useAPIUtils } from "@/components/APIUtilsProvider";
import { clear as clearTokenInfo } from "@/utils/userInfoUtils";
import {
  ActionIcon,
  AppShell,
  Avatar,
  Center,
  Divider,
  Flex,
  Group,
  Image,
  Menu,
  rem,
  Text,
} from "@mantine/core";
import { useFullscreen, useLocalStorage } from "@mantine/hooks";
import { notifications } from "@mantine/notifications";
import { IconLogout, IconTool } from "@tabler/icons-react";
import { useNavigate } from "react-router-dom";

function WithwingsHeader() {
  const { toggle: toggleFullscreen, fullscreen } = useFullscreen();

  const { tanstackQuery, tanstackInvalidate } = useAPIUtils();

  let currentUserInfoQuery = tanstackQuery(`/api/me`);

  const [themeName, setThemeName] = useLocalStorage({
    key: "theme-name",
    defaultValue: "earl",
  });

  const navigate = useNavigate();

  const doLogout = async () => {
    await clearTokenInfo();
    await tanstackInvalidate();
    navigate("/login");
    setTimeout(() => {
      notifications.clean();

      notifications.show({
        color: "teal",
        title: "您已退出登录",
      });
    }, 100);
  };

  return (
    <AppShell.Header>
      <Group h="100%" px="md" justify="space-between" p="sm">
        <Flex
          h={"100%"}
          w="500"
          gap="8"
          justify="flex-start"
          align="center"
          direction="row"
          wrap="wrap"
        >
          <Image src={"/joymart.png"} w={40} h={40} />
          <Text size="xl" fw={600}>
            运营平台
          </Text>
        </Flex>

        <Group gap={"xs"}>
          <ActionIcon
            size={42}
            radius={"lg"}
            variant="default"
            onClick={() => window.open(`/settings`, "_blank")}
          >
            <IconTool style={{ width: rem(24), height: rem(24) }} />
          </ActionIcon>

          <Menu shadow="md" trigger="hover" width={200}>
            <Menu.Target>
              <Avatar
                size={40}
                variant="outline"
                radius="lg"
                src={currentUserInfoQuery.data?.user.meta.avatar}
              />
            </Menu.Target>

            <Menu.Dropdown>
              <Center maw={200} h={200} bg="var(--mantine-color-gray-light)">
                <Avatar
                  size={"90%"}
                  variant="outline"
                  radius="lg"
                  src={currentUserInfoQuery.data?.user.meta.avatar}
                />
              </Center>
              <Divider label={currentUserInfoQuery.data?.user.nickname} />

              <Menu.Item
                leftSection={
                  <IconLogout style={{ width: rem(14), height: rem(14) }} />
                }
                onClick={() => doLogout()}
              >
                注销
              </Menu.Item>
            </Menu.Dropdown>
          </Menu>
        </Group>
      </Group>
    </AppShell.Header>
  );
}

export default WithwingsHeader;
